package com.atguigu.eduservice.listener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.ExcelSubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.handler.CustomException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DemoDataListener extends AnalysisEventListener<ExcelSubjectData> {

	private EduSubjectService eduSubjectService;

	public DemoDataListener() {
	}

	public DemoDataListener(EduSubjectService eduSubjectService) {
		this.eduSubjectService = eduSubjectService;
	}

	@Override
	public void invoke(ExcelSubjectData eduSubject, AnalysisContext analysisContext) {
		if (eduSubject==null){
			throw new CustomException(2001,"数据文件为空");
		}

		//添加一级分类
		EduSubject existOneSubject = this.existOneSubject(eduSubjectService,eduSubject.getOneSubjectName());

		if(existOneSubject == null) {//没有相同的
			existOneSubject = new EduSubject();
			existOneSubject.setTitle(eduSubject.getOneSubjectName());
			existOneSubject.setParentId("0");
			eduSubjectService.save(existOneSubject);
		}

		//获取一级分类id值
		String pid = existOneSubject.getId();

		//添加二级分类
		EduSubject existTwoSubject = this.existTwoSubject(eduSubjectService,eduSubject.getTwoSubjectName(), pid);

		if(existTwoSubject == null){
			existTwoSubject = new EduSubject();
			existTwoSubject.setTitle(eduSubject.getTwoSubjectName());
			existTwoSubject.setParentId(pid);
			eduSubjectService.save(existTwoSubject);
		}
	}
	//判断一级分类是否重复
	private EduSubject existTwoSubject(EduSubjectService subjectService,String name,String pid) {
		QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
		wrapper.eq("title",name);
		wrapper.eq("parent_id",pid);
		EduSubject eduSubject = subjectService.getOne(wrapper);
		return eduSubject;
	}

	//判断一级分类是否重复
	private EduSubject existOneSubject(EduSubjectService subjectService,String name) {
		QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
		wrapper.eq("title",name);
		wrapper.eq("parent_id","0");
		EduSubject eduSubject = subjectService.getOne(wrapper);
		return eduSubject;
	}

	@Override
	public void doAfterAllAnalysed(AnalysisContext analysisContext) {

	}
}
